﻿using System.Collections.Generic;
using System.Linq;

namespace Basmus.Values
{
    public class CompositeValuesProvider<TValue> : IValuesProvider<TValue>
    {
        private readonly bool _merge;
        private readonly IEnumerable<IValuesProvider<TValue>> _valueProviders;

        public CompositeValuesProvider(IEnumerable<IValuesProvider<TValue>> valueProviders, bool merge)
        {
            _merge = merge;
            _valueProviders = valueProviders.ToArray();
        }

        public IEnumerable<string> GetNames()
        {
            var names= _valueProviders
                .SelectMany(x => x.GetNames())
                .Distinct();
            return names;
        }

        public IEnumerable<TValue> GetValues(string name)
        {
            if (_merge)
            {
                var all = _valueProviders
                    .Select(x => x.GetValues(name))
                    .Where(x => x != null)
                    .SelectMany(x => x);
                return all;
            }
            var first = _valueProviders
                .Select(x => x.GetValues(name))
                .FirstOrDefault(x => x != null);
            return first;

        }
    }
}